//
//  EditViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/27.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import AFNetworking

class EditViewController: KMViewController {

    fileprivate var tableView : UITableView!
    
    fileprivate let pickVC = KMImagePickerViewController()//照片相册代理
    
    fileprivate let avatarCell = "avatarCell"
    fileprivate let editCell = "editCell"
    
    fileprivate let dataArray = [avatar_title,nickName_title,idAccount_title,changePassword,bindingPhone,bindMailbox,verifyName_title]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.editColor()
        
        self.title = editPerson_news
        pickVC.delegate = self
        createTableView()
        verification()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        if tableView != nil {
            tableView.reloadData()
        }
    }
    
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        let footerView = EditFooterView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 70)))
        footerView.signOutBtn.addTarget(self, action: #selector(signOutAction), for: .touchUpInside)
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = footerView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(EditCell.self, forCellReuseIdentifier: editCell)
        tableView.register(EditAvatarCell.self, forCellReuseIdentifier: avatarCell)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }
    
    //MARK: 实名验证
    fileprivate func verification() {
        
        KMTool.requestMethod(.post, URLString: url_verify, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? ""], success: { (value, json) in
            
            if json["status"] == "0" {
                KMTool.setObject(json["auth"].stringValue, forEnumKey: .verify)
                self.tableView.reloadData()
            }
        }) {
            
        }
    }
    
    //MARK: 修改昵称
    fileprivate func changNickName() {
        
        let alertVC = UIAlertController.init(title: nickName_title, message: nil, preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: global_confirm, style: .default) { (alert) in
            
            for textField in alertVC.textFields! {
                
                if textField.text == "" {
                    KMTool.showText(_text: inputNickName)
                    return
                }
                
                KMTool.requestData(URLString: url_changeNickName, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? "","username":textField.text!], success: { (string) in
                    
                    if string == "0" {
                        KMTool.setObject(textField.text, forEnumKey: .userName)
                        KMTool.showText(_text: changeSuccess)
                        self.tableView.reloadData()
                    }else{
                        KMTool.showText(_text: changeFail)
                    }
                })
            }
        }
        
        let cancelAction = UIAlertAction.init(title: global_cancel, style: .cancel, handler: nil)
        alertVC.addTextField { (textField) in
            textField.placeholder = inputNickName
            textField.text = KMTool.stringForEnumKey(.userName)
        }
        
        alertVC.addAction(okAction)
        alertVC.addAction(cancelAction)
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    //MARK: 退出登录
    @objc fileprivate func signOutAction() {
        
        KMTool.setAlertView(msg: confirmSignOut, target: self, haveCancel: true) { (alert) in
            
            KMTool.clearUserNews() //清除用户信息
            self.navigationController?.popViewController(animated: true)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension EditViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 0 {
            return 80
        }else{
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
       
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: avatarCell, for: indexPath) as? EditAvatarCell
            if let avatar = KMTool.stringForEnumKey(.avatar) {
                if avatar == "" {
                    cell?.avatarImage.image = #imageLiteral(resourceName: "avatar_default")
                }else{
                    cell?.avatarImage.image = KMTool.base64ToImage(base: avatar)
                }
                
            }
            
            cell?.titleLabel.text = dataArray[indexPath.row]
            cell?.accessoryType = .disclosureIndicator
            return cell!
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: editCell, for: indexPath) as? EditCell
            cell?.leftLabel.text = dataArray[indexPath.row]
            cell?.accessoryType = .disclosureIndicator
            
            switch indexPath.row {
            case 1:
                cell?.rightLabel.text = KMTool.stringForEnumKey(.userName)
            case 2:
                cell?.rightLabel.text = KMTool.stringForEnumKey(.phone)
            case 4:
                cell?.rightLabel.text = bounded
            case 5:
                cell?.rightLabel.text = unbound
            case 6:
                if let verified = KMTool.stringForEnumKey(.verify) {
                    if verified == "0" {
                        cell?.rightLabel.text = unVerify
                    }else{
                        cell?.rightLabel.text = verify
                    }
                }
            default:
                break
                
            }
            
            return cell!
        }
        
        
        
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        switch indexPath.row {
        case 0:
            self.touchAvator()
        case 1:
            self.changNickName()
        case 3:
        self.navigationController?.pushViewController(ChangeViewController(), animated: true)
        case 4:
            self.navigationController?.pushViewController(BindPhoneViewController(), animated: true)
        case 6:
            if let verified = KMTool.stringForEnumKey(.verify) {
                if verified == "0" {
                    self.navigationController?.pushViewController(VerifyViewController(), animated: true)
                }else{
                    self.navigationController?.pushViewController(MessageViewController(), animated: true)
                }
            }
        
            
        default:
            break
        }
    }
}


extension EditViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //MARK: 点击头像
    fileprivate func touchAvator() {
        
        KMTool.setBottomAlertView(title: updateAvatar, msg: nil, target: self, actionTitle: [takePhoto,selectFromAlbum]) {[weak self] (alert) in
            
            switch alert.title {
            case takePhoto:
                self?.openCamera()
            case selectFromAlbum:
                self?.openPhotots()
            default:
                break
            }
        }
        
        
    }
    
    //MARK: 照相
    fileprivate func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            pickVC.sourceType = .camera
            pickVC.allowsEditing = true
        self.pickVC.navigationController?.navigationBar.isTranslucent = false
            self.present(pickVC, animated: true, completion: nil)
        }else{
            KMTool.showText(_text: "模拟器")
        }
    }
    
    //MARK: 相册
    fileprivate func openPhotots() {
        pickVC.sourceType = .photoLibrary
        pickVC.allowsEditing = true
        self.present(pickVC, animated: true, completion: nil)
    }
    
    //MARK: 选择图片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let headImage = info[UIImagePickerControllerEditedImage] as? UIImage //选中图片
        let headImageDate = UIImageJPEGRepresentation(headImage ?? UIImage(), 0.5) //图片压缩
//        let url_uploadfile = KMTool.docDir + "/avatar.png" //将图片存到本地沙盒
//        FileManager.default.createFile(atPath: url_uploadfile, contents: headImageDate, attributes: nil)
        
        
        KMTool.requestData(URLString: url_changeAvatar, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? "","img":headImageDate?.base64EncodedString() ?? ""]) { (string) in
            
            
            if string == "0" {
                KMTool.setObject(KMTool.imageToBase64(image: headImage!), forEnumKey: .avatar)
                KMTool.showText(_text: changeSuccess)
                self.tableView.reloadData()
                
            }else{
                KMTool.showText(_text: changeFail)
            }
        }
        
        self.pickVC.dismiss(animated: true, completion: nil)
        
    }
    
    
}
